package com.xnj.testweb.admin.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.xnj.testweb.core.entry.SysUser;
import org.springframework.stereotype.Service;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Service
public class ExportService {

    public void exportToExcel(OutputStream outputStream) throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();

        // 创建 ExcelWriter，直接写入 OutputStream
        ExcelWriter excelWriter = EasyExcel.write(outputStream, SysUser.class).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").build();

        int totalRows = 200000;
        int batchSize = 10000;
        int threadCount = 10;

        ExecutorService executor = Executors.newFixedThreadPool(threadCount);
        List<Future<List<SysUser>>> futures = new ArrayList<>();

        // 分配任务给线程
        for (int i = 0; i < totalRows; i += batchSize) {
            int start = i;
            int end = Math.min(i + batchSize, totalRows);
            futures.add(executor.submit(() -> getBatchData(start, end)));
        }

        // 收集所有线程的结果并写入 Excel
        for (Future<List<SysUser>> future : futures) {
            List<SysUser> batchData = future.get();
            excelWriter.write(batchData, writeSheet);
        }

        // 关闭资源
        excelWriter.finish();
        executor.shutdown();

        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        System.out.println("导出完成，总耗时：" + executionTime + " 毫秒");
    }

    private List<SysUser> getBatchData(int start, int end) {
        List<SysUser> batchData = new ArrayList<>();
        for (int i = start; i < end; i++) {
            SysUser user = new SysUser();
            user.setUserName("张" + i);
            user.setPassword("测试");
            user.setUserRole("admin");
            user.setRealName("章三年");
            user.setUserType("admin");
            user.setPhoneNumber("11111111111");
            user.setUserMail("123@163.com");
            user.setDepartment("开发");
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            batchData.add(user);
        }
        return batchData;
    }
}